<?php

/**
 * Created by PhpStorm.
 * User: liuweiping
 * Date: 16/7/18
 * Time: 14:53
 */
// 232 : 开发用的服务
//define('API_HOST', 'http://10.0.1.232:9024');
// 235 : 测试用的服务
//define('API_HOST', 'http://10.0.1.235:9024');
require_once 'host_helper.php';

// 定义错误码
/**
 * 成功
 */
define('SUCCESS', 0);
/**
 * 参数为空
 */
define('ERROR_NO_PARAMS', 0xABC001);
/**
 * 参数错误，例如缺少service字段
 */
define('ERROR_PARAMS', 0xABC002);
/**
 * 未登录
 */
define('ERROR_NO_LOGIN', 0xABC003);
/**
 * 请求服务器失败
 */
define('ERROR_NO_RESPONSE', 0xABC004);
/**
 * 服务器返回为空
 */
define('ERROR_EMPTY_RESPONSE', 0xABC005);
/**
 * 服务器返回为空
 */
define('ERROR_NONSUPPORT_AJAX', 0xABC006);

/**
 * 用户名和密码登录
 * @param $username
 * @param $password
 * @param $campus_id
 * @return string
 * @internal param $code
 */
function login($username, $password, $campus_id)
{
    $params = array(
        'phone' => $username,
        'passwd' => $password,
        'oper_cid' => $campus_id,
    );
    return api_request('rosefinch.web.staff.login', $params);
}

/**
 * 构造请求URL
 * @param $service
 * @param array $params post键值对数据; 不需要包含固定参数
 * @return mixed 请求结果
 */
function api_request($service, $params = [], $header = [], $files = null)
{
    $params = fixCommonParams($params);
    $url = API_HOST . str_replace('.', '/', $service);
    // 添加文件上传
    if ($files != null) {
        log_message('error', 'FILE [POST] <' . $service . '> ' . json_encode($files));
        foreach ($files as $key => $file) {
            $file_path = $file['tmp_name'];
            $file_type = $file['type'];
            $file_name = $file['name'];

            $fileObj = new CURLFile(realpath($file_path), $file_type, $file_name);
            $params[$key] = $fileObj;
        }
    } else {
        //
        $params = http_build_query($params);
    }
    log_message("error", 'HEADER <' . $service . "> " . $url . " -> " . json_encode($header));
    log_message("error", 'REQUEST <' . $service . "> " . $url . " -> " . json_encode($params));
    return postData($url, $params, $header);
}

/**
 * 在原参数的基础上,添加固定参数.
 * @param $params
 * @return mixed
 */
function fixCommonParams($params = [])
{
    $CI =& get_instance();
    $session_user = $CI->session->session_user;
//    log_message('error', 'fixCommonParams Session: ' . json_encode($CI->session));
    $user = [];
    if (!empty($session_user)) {
        $user = array(
            'oper_uid' => array_key_exists('id', $session_user) ? $session_user['id'] : 0,
            'oper_aid' => array_key_exists('oper_aid', $session_user) ? $session_user['oper_aid'] : 0,
            'oper_gid' => array_key_exists('oper_gid', $session_user) ? $session_user['oper_gid'] : 0,
            'oper_cid' => array_key_exists('campus_id', $session_user) ? $session_user['campus_id'] : 0
        );
    }
    // $user 在后，覆盖前端传入的$params参数
    $params = array_merge($params, $user);
    return $params;
}

/**
 * @param $url
 * @param $data
 * @param null $header
 * @return mixed
 */
function postData($url, $data, $header = [])
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    $handles = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    log_message('error', 'SERVER < ' . $url . '> HttpCode : ' . $httpCode);
    curl_close($ch);
    return $handles;
}

/**
 * @param $url
 * @param $data
 * @param null $header
 * @return array keys : [header, content]
 */
function url_download($service, $data, $header = [])
{
//    $url = API_HOST . ' / mweb / ' . str_replace(' . ', ' / ', $service);
    $url = API_HOST . str_replace('.', '/', $service) . '?' . http_build_query($data);
    //. '?' . http_build_query($data);
    log_message('error', 'DOWNLOAD <' . $service . '> URL-> ' . $url);

    redirect($url);
    return $url;
}

/**
 * @param int $code 错误码，默认：0
 * @param string $msg 错误信息，默认：SUCCESS
 * @return string JSON格式的响应内容
 */
function getError($code = 0, $msg = 'SUCCESS')
{
    $CI =& get_instance();
    $header = $CI->input->request_headers();
    $accept = $header['Accept'];
    if (strstr($accept, 'application/json')) {
        header('Content-type:application/json; charset=UTF - 8');
    } else if (strstr($accept, 'text/html')) {
        header('Content-type:text/html; charset=UTF-8');
    }
    log_message('error', 'getError # CODE = ' . $code . '; MSG = ' . $msg . '; header = ' . json_encode($header));
    return json_encode(array(
        'code' => $code,
        'msg' => $msg,
        'from' => 'PHP'
    ));
}

/**
 * @param $body
 * @return string
 */
function getSuccess($body)
{
    log_message('error', 'getSuccess # BODY = ' . json_encode($body));

    $CI =& get_instance();
    $header = $CI->input->request_headers();
    $accept = $header['Accept'];
    if (strstr($accept, 'application/json')) {
        header('Content-type:application/json; charset=UTF-8');
    } else if (strstr($accept, 'text/html')) {
        header('Content-type:text/html; charset=UTF-8');
    }
    return json_encode(array(
        'code' => 0,
        'msg' => 'SUCCESS',
        'body' => $body,
        'from' => 'PHP'
    ));
}
